from datetime import date, timedelta, datetime

from django.contrib.auth import authenticate
from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import render

# Create your views here.
from django.views import View

# 后台登陆
from fdfs_client.client import Fdfs_client
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, ListCreateAPIView, CreateAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import GoodsVisitCount, SKUImage, SKU, SPU, GoodsCategory, SPUSpecification, SpecificationOption, \
    Brand, GoodsChannel, GoodsChannelGroup
from apps.meiduo_admin.serializers.all import My_all_spuSerializer, SPU_specification_serializer, \
    SpecificationOption_serializer, ADD_SpecificationOption_serializer, Order_serializer, ADD_SPU_brand_Serializer, \
    SPU_category1_serialize, PermissionSerializer, ContentType_Serializer, GroupSerializer, AdminSerializer, \
    GoodsChannel_Serializer, Brand_Serializer, GoodsChannelGroup_Serializer
from apps.meiduo_admin.serializers.catagory import GoodsSerializer
from apps.meiduo_admin.serializers.sku import SKUSerializer, catagory_serializer, Add_SPU_serializer

from apps.meiduo_admin.serializers.sku_image import SKU_Image_Serializer, Add_all_skuSerializer
from apps.meiduo_admin.serializers.user import UserSerilizer
from apps.meiduo_admin.utils import MeiduoModelBackend, PageNum
from apps.orders.models import OrderInfo
from apps.users.models import User


# 统计月累计日增加用户
class UserMonthCountView(APIView):
    # 只有管理员可以进入
    # permission_classes = [permissions.IsAuthenticated]
    # 获取30天前日期
    def get(self, request):
        month_ago = date.today() - timedelta(30)
        good_list = []
        # 遍历每一天
        for i in range(30):
            that_day = month_ago + timedelta(i)

            # 要查询的是那一天日期和下一天日期之间
            count = User.objects.filter(date_joined__gte=that_day, date_joined__lte=that_day + timedelta(i)).count()
            good_list.append({
                'count': count,
                'date': that_day
            })
        return Response(good_list)


# 用户总量统计
class UserTotalCountView(APIView):
    def get(self, request):
        count = User.objects.all().count()
        today = date.today()
        return Response({
            "count": count,
            'date': today
        })


# 日增用户
class UserDayCountView(APIView):
    # permission_classes = [permissions.IsAuthenticated]
    def get(self, request):
        today = date.today()
        count = User.objects.filter(date_joined__gte=today).count()
        return Response({
            'date': today,
            'count': count
        })


# 日活跃用户
class UserActiveCountView(APIView):
    def get(self, request):
        today = date.today()
        count = User.objects.filter(last_login__gte=today).count()
        return Response({
            'date': today,
            'count': count
        })


# 日下单用户
class UserOrderCountView(APIView):
    def get(self, request):
        today = date.today()
        count = OrderInfo.objects.filter(create_time__gte=today).count()
        return Response({
            'date': today,
            'count': count
        })


# 日分类商品访问量
class GoodsDayView(APIView):
    def get(self, request):
        today = date.today()
        data = GoodsVisitCount.objects.filter(create_time__gte=today)
        info = GoodsSerializer(data, many=True)
        return Response(info.data)


# 查询用户,新增用户
class UserListView(ListCreateAPIView):
    # 三级视图省略了get 和return self.list  list里面有排序
    # 定义序列化器
    serializer_class = UserSerilizer
    # 自定义分页器
    pagination_class = PageNum

    # 获得查询集
    # def get_serializer_class(self):
    #     if self.request.method == 'GET':
    #         return UserSerilizer
    #     elif self.request.method == 'POST':
    #         return UserAddSerializer
    def get_queryset(self):
        user_name = self.request.query_params.get('keyword')
        # 如果有传入username 那就查询单个 ,如果没有则显示全部
        if not user_name:
            return User.objects.all()
        else:
            return User.objects.filter(username=user_name)
            # 查询用户,因为继承了三级视图有get自动return self.list 调用分页,重写分页返回数据
            # 新增用户，因为继承了三级视图有post和creat了,新增用户重写一下creat方法.
            # 自动有post 和 creat


            # def post(self,request):
            #     #获得参数
            #     password = request.data.get('password')
            #     username = request.data.get('username')
            #     mobile = request.data.get('mobile')
            #     email = request.data.get('email')
            #
            #     #校验参数
            #
            #     #写入
            #     try:
            #         user = User.objects.create_user(password=password,username=username,mobile=mobile,email=email)
            #
            #     except Exception:
            #         return None
            #     return Response({
            #         'id':user.id,
            #         'username':user.username,
            #         'mobile':user.mobile,
            #         'email':user.email
            #     })


'''------------------图片-------------------'''


# SKU图片管理
class ImageViewSet(ModelViewSet):
    # 继承了所有的Mixin类
    queryset = SKUImage.objects.all()
    serializer_class = SKU_Image_Serializer
    pagination_class = PageNum

    # def get(self,request):
    #     return self.list(request)

    # 重写createMIxin的保存方法实现保存图片
    def create(self, request, *args, **kwargs):
        # 创建FDFS实例对象
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 从请求中获取图片
        data = request.FILES.get('image')
        # 客户端上传到fastDFS 图片转二进制
        ret = client.upload_by_buffer(data.read())

        # 判断是否成功
        if ret["Status"] != 'Upload successed.':
            return Response(status=403)

        # 如果上传成功获取图片路径
        image_url = ret['Remote file_id']
        # 表单中选择的sku获取sku_id
        sku_id = request.data.get('sku')
        # 保存图片
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        return Response({
            'id': img.id,
            'sku': sku_id,
            'image': img.image.url
        }, status=201)

    # 重写更新
    def update(self, request, *args, **kwargs):
        # 再上传一张到远程 获取的url再修改表中的
        # 获取图片资源
        data = request.FILES.get('image')
        # 创建FDFS实例对象
        client = Fdfs_client('utils/fastdfs/client.conf')
        ret = client.upload_by_buffer(data.read())  # 上传
        # 如果上传失败返回403
        if ret['Status'] != 'Upload successed.':
            return Response(status=403)
        # 如果成功获取存储的url
        url = ret['Remote file_id']
        sku_id = request.data.get('sku')  # 只是用来返回用,并不唯一不能用来找
        #
        # 修改表中数据
        img = SKUImage.objects.get(id=kwargs['pk'])
        img.image = url
        img.save()
        return Response({
            'id': img.id,
            'sku': img.sku.id,
            'image': img.image.url

        }, status=201)


# 新增图片获取所有sku id和name
class ImageAdd_get_skuView(ListAPIView):
    # 用三级视图没有get return
    # 需要序列化器和查询集
    queryset = SKU.objects.all()
    serializer_class = Add_all_skuSerializer
    # 自己get 自己return


'''------------------SKU-------------------'''


# sku数据视图集
class SKUModelViewSet(ModelViewSet):
    serializer_class = SKUSerializer
    pagination_class = PageNum

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        # 如果有传入keyword 返回单独这一个
        # count = SKU.objects.filter(name__contains=keyword).count()
        if keyword is None:
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)


# 新增商品中的分类
class AddCategoryView(ListAPIView):
    # 三级分类subs=None
    queryset = GoodsCategory.objects.filter(subs=None)
    serializer_class = catagory_serializer


# 新增商品中的SPU信息
class AddSPUView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = Add_SPU_serializer


# 新增商品中的SPU规格信息
class ADDSPUoptionsView(ListAPIView):
    # queryset = SpecificationOption.objects.all()
    serializer_class = SPU_specification_serializer

    # 只查找spu_id = pk的规格信息
    def get_queryset(self):
        return SPUSpecification.objects.filter(spu_id=self.kwargs['pk'])


# 新增SPU中的一级分类
class SPU_category(ListAPIView):
    queryset = GoodsCategory.objects.filter(parent=None)
    serializer_class = SPU_category1_serialize


class SPU_category2(ListAPIView):
    def get_queryset(self):
        return GoodsCategory.objects.filter(parent=self.kwargs['pk'])
    serializer_class = SPU_category1_serialize

# 所有SPU表视图集
class SPUModelViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    # all_spuSerializer
    serializer_class = My_all_spuSerializer
    pagination_class = PageNum



# 商品规格视图集
class SPU_specification_ViewSet(ModelViewSet):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPU_specification_serializer
    pagination_class = PageNum


# 规格选项视图集
class specification_options_ViewSet(ModelViewSet):
    queryset = SpecificationOption.objects.all()
    serializer_class = SpecificationOption_serializer
    pagination_class = PageNum


# 规格选项管理中的规格信息
class ADD_Option(ListAPIView):
    queryset = SpecificationOption.objects.all()
    serializer_class = SpecificationOption_serializer


# 新增spu表中的品牌
class ADD_SPU_brand(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = ADD_SPU_brand_Serializer


# 订单视图集
class OrderViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = Order_serializer
    pagination_class = PageNum

    # 防止恶意删除
    def destroy(self, request, *args, **kwargs):
        return Response({'msg': 'error'})

    # 修改订单状态
    @action(methods=['PUT'], detail=True)
    def status(self, request, pk):
        order = OrderInfo.objects.get(order_id=pk)
        status = request.data.get('status')
        order.status = status
        order.save()
        return Response({
            'order_id': order.order_id,
            'order.status': order.status
        })


# 权限管理视图集

class PermissionViewSet(ModelViewSet):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    pagination_class = PageNum


class ContentTypeListAPIView(ListAPIView):
    queryset = ContentType.objects.all()
    serializer_class = ContentType_Serializer


# 用户组管理
class GroupViewSet(ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    pagination_class = PageNum


# 获取用户组中权限表数据
class GroupContentListAPIView(ListAPIView):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer


# 管理员管理
class AdminView(ModelViewSet):
    queryset = User.objects.filter(is_staff=True)
    serializer_class = AdminSerializer
    pagination_class = PageNum


# 管理员管理中修改信息获取用户组
class AdminGroupListAPIView(ListAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


# 一级分类id 外键中的外键
# class
# 频道管理
class ChannelsViewSet(ModelViewSet):
    queryset = GoodsChannel.objects.all()
    serializer_class = GoodsChannel_Serializer
    pagination_class = PageNum


# 频道管理中的新增   显示频道组信息



class channel_types(ListAPIView):
    queryset = GoodsChannel.objects.all()
    serializer_class = GoodsChannelGroup_Serializer


# 频道管理中的新增   显示分类信息
class Goods_Categories(ListAPIView):
    queryset = GoodsCategory.objects.filter(parent=None)
    serializer_class = SPU_category1_serialize


# 品牌管理视图集
class Goods_Brands(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = Brand_Serializer
    pagination_class = PageNum
    def create(self, request, *args, **kwargs):
        client = Fdfs_client('utils/fastdfs/client.conf')
        data = request.FILES.get('logo')
        ret = client.upload_by_buffer(data.read())
        if ret["Status"] != 'Upload successed.':
            return Response(status=403)

        #获取图片url
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        url = ret.get('Remote file_id')
        #写入品牌表中
        brand = Brand.objects.create(name=name,logo=url,first_letter=first_letter)
        return Response({
            'id':brand.id,
            'name':brand.name,
            'first_letter':first_letter,
            'logo':url,
        }, status=201)


    def update(self, request, *args, **kwargs):
        pk = kwargs.get('pk')

        client = Fdfs_client('utils/fastdfs/client.conf')
        pic = request.FILES.get('logo','no_pic')
        #因为前端写死了 没有上传图片不让提交 所以都是有图片的
        ret = client.upload_appender_by_buffer(pic.read())
        if ret["Status"] != 'Upload successed.':
            return Response(status=403)
        #更新
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        url = ret.get('Remote file_id')
        Brand.objects.filter(id=pk).update(name=name,first_letter=first_letter,logo=url)
        return Response({
            'id': pk,
            'name': name,
            'first_letter': first_letter,
            'logo': url,
        }, status=201)